#include "server.h"

WebSocketServer::WebSocketServer(QObject *parent) : QObject(parent)
{
    m_server = new QWebSocketServer("My Qt Server", QWebSocketServer::NonSecureMode, this);

    if (m_server->listen(QHostAddress::Any, 8080)) {
        qDebug() << "WebSocket服务器已启动，监听端口8080";
        connect(m_server, &QWebSocketServer::newConnection, this, &WebSocketServer::onNewConnection);
    } else {
        qDebug() << "WebSocket服务器启动失败:" << m_server->errorString();
    }
}

void WebSocketServer::broadcastMessage(const QString &message)
{
    for (QWebSocket *client : qAsConst(m_clients)) {
        client->sendTextMessage(message);
    }
}

void WebSocketServer::broadcastJson(const QJsonObject &jsonObj)
{
    QJsonDocument doc(jsonObj);
    QString message = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
    broadcastMessage(message);
}

void WebSocketServer::sendMessageToClient(QWebSocket *client, const QString &message)
{
    if (client && m_clients.contains(client)) {
        client->sendTextMessage(message);
    }
}

void WebSocketServer::sendJsonToClient(QWebSocket *client, const QJsonObject &jsonObj)
{
    QJsonDocument doc(jsonObj);
    QString message = QString::fromUtf8(doc.toJson(QJsonDocument::Compact));
    sendMessageToClient(client, message);
}

void WebSocketServer::sendMessageToClientByAddress(const QString &address, const QString &message)
{
    for (QWebSocket *client : qAsConst(m_clients)) {
        if (client->peerAddress().toString() == address) {
            sendMessageToClient(client, message);
            break;
        }
    }
}

void WebSocketServer::leftWin(const bool &has_avatar, const int &index, const QString &name, const QString &headImgUrl, const QString &content, const QString &id)
{
    qDebug() << "弹窗函数执行了";
    QJsonObject message;
    message["type"]     = "left";
    message["name"]     = name;
    message["content"]  = content;
    message["id"]       = id;
    message["avatar"]   = headImgUrl;

    if (!has_avatar)
    {
        message["has_avatar"] = has_avatar;
        message["avatar"] = index;
    }

    if (QWebSocket* client = findClientByName("popover")) {
        sendJsonToClient(client, message);
        qDebug() << "左边弹窗";
    }
}

void WebSocketServer::rightWin(const bool &has_avatar, const int &index, const QString &name, const QString &headImgUrl, const QString &content, const QString &id)
{
    QJsonObject message;
    message["type"]     = "right";
    message["name"]     = name;
    message["content"]  = content;
    message["id"]       = id;
    message["avatar"]   = headImgUrl;

    if (!has_avatar)
    {
        message["has_avatar"] = has_avatar;
        message["avatar"] = index;
    }

    qDebug() << message;
    if (QWebSocket* client = findClientByName("popover")) {
        sendJsonToClient(client, message);
    }
}

void WebSocketServer::leftGiftWin(const bool &has_avatar, const int &index, const QString &name, const QString &headImgUrl, const QString &content, const QString &id)
{
    qDebug() << "左礼物弹窗执行了";
    QJsonObject message;
    message["type"]     = "left_gift";
    message["name"]     = name;
    message["content"]  = content;
    message["id"]       = id;
    message["avatar"]   = headImgUrl;
    if (!has_avatar)
    {
        message["has_avatar"] = has_avatar;
        message["avatar"] = index;
    }

    if (QWebSocket* client = findClientByName("popover")) {
        sendJsonToClient(client, message);
        qDebug() << "左边弹窗";
    }
}

void WebSocketServer::rightGiftWin(const bool &has_avatar, const int &index, const QString &name, const QString &headImgUrl, const QString &content, const QString &id)
{
    QJsonObject message;
    message["type"]     = "right_gift";
    message["name"]     = name;
    message["content"]  = content;
    message["id"]       = id;
    message["avatar"]   = headImgUrl;

    if (!has_avatar)
    {
        message["has_avatar"] = has_avatar;
        message["avatar"] = index;
    }

    qDebug() << message;
    if (QWebSocket* client = findClientByName("popover")) {
        sendJsonToClient(client, message);
    }
}

void WebSocketServer::additem(const QString &player_id, const QString &player_name, const QString &player_HeadImgUrl, const QString &team, const QString &content, const int& progress, const QString& prefix)
{
    QJsonObject message;
    message["team"]         = team;
    message["player_id"]    = player_id;
    message["player_name"]  = player_name;
    message["content"]      = content;
    message["avatar"]       = player_HeadImgUrl;
    message["progress"]     = progress;
    message["prefix"]       = prefix;
    message["type"]         = "add";

    if (QWebSocket* client = findClientByName("GameUI")) {
        sendJsonToClient(client, message);
        qDebug() << "给GameUI发送【添加用户】成功";
    }
}

void WebSocketServer::delitem(const QString &player_id, const QString &player_name) {
    qDebug() << "准备删除用户" << player_name;
    QJsonObject message;
    message["player_id"]    = player_id;
    message["player_name"]  = player_name;
    message["type"]         = "del";

    if (QWebSocket* client = findClientByName("GameUI")) {
        sendJsonToClient(client, message);
        qDebug() << "给GameUI发送【删除用户】成功";
    }
}

void WebSocketServer::onClearUI() {
    QJsonObject message;
    message["type"] = "clear";

    if (QWebSocket* client = findClientByName("GameUI")) {
        sendJsonToClient(client, message);
        qDebug() << "给GameUI发送【清空UI通知】成功";
    }
}

void WebSocketServer::onClearPopover() {
    QJsonObject message;
    message["type"] = "clear";

    if (QWebSocket* client = findClientByName("popover")) {
        sendJsonToClient(client, message);
        qDebug() << "给弹窗程序发送【清空消息队列】成功";
    }
}

void WebSocketServer::showRanking() {
    QJsonObject message;
    message["type"] = "show";

    if (QWebSocket* client = findClientByName("popover")) {
        sendJsonToClient(client, message);
        qDebug() << "给popover发送【显示排行榜】成功";
    }
}

QString WebSocketServer::getClientNameByIP(const QString &ip) const
{
    QWebSocket *client = m_clientIPs.value(ip);
    return client ? m_clientNames.value(client) : QString();
}

void WebSocketServer::changePlayerSort(const QString &userId, const int &sortValue) {
    QJsonObject message;
    message["type"] = "changeSort";
    message["player_id"] = userId;
    message["sortValue"] = sortValue;

    if (QWebSocket* client = findClientByName("GameUI")) {
        sendJsonToClient(client, message);
        qDebug() << "给popover发送【改变排序】成功";
    }
}

void WebSocketServer::showLeaderboard_cs(const QJsonObject &message) {
    if (QWebSocket* client = findClientByName("Leaderboard_CS")) {
        sendJsonToClient(client, message);
        qDebug() << "给Leaderboard_CS发送【显示排行榜】成功";
    }
}

void WebSocketServer::printConnectedClients() const
{
    qDebug() << "当前在线客户端列表:";
    for (auto it = m_clientNames.begin(); it != m_clientNames.end(); ++it) {
        QWebSocket *client = it.key();
        qDebug()
            << "名称:" << it.value()
            << "IP:" << client->peerAddress().toString();
    }
}

void WebSocketServer::killBroadcast(const Player killer, const Player victim, const int killVoice)
{
    QJsonObject message, killerObj, victimObj;
    killerObj["name"]   = killer.name;
    killerObj["avatar"] = killer.avatar;
    killerObj["id"]     = killer.id;

    victimObj["name"]   = victim.name;
    victimObj["avatar"] = victim.avatar;
    victimObj["id"]     = victim.id;

    message["killer"]    = killerObj;
    message["victim"]    = victimObj;
    message["killVoice"] = killVoice;

    message["type"] = "broadcast";

    if (QWebSocket* client = findClientByName("GameUI")) {
        sendJsonToClient(client, message);
        qDebug() << "给GameUI发送【显示击杀播报】成功";
    }
}


void WebSocketServer::clearKillBroadcast()
{
    QJsonObject message;
    message["type"] = "clearBroadcast";

    if (QWebSocket* client = findClientByName("GameUI")) {
        sendJsonToClient(client, message);
        qDebug() << "给GameUI发送【清空击杀播报】成功";
    }
}


void WebSocketServer::onNewConnection()
{
    QWebSocket *socket = m_server->nextPendingConnection();

    QString clientAddress = socket->peerAddress().toString();
    quint16 clientPort = socket->peerPort();

    // 连接信号槽，处理首次连接消息
    connect(socket, &QWebSocket::textMessageReceived, this, [this, socket, clientAddress](const QString &message) {
        qDebug()
        << "收到客户端首次连接消息:" << message
        << "来自IP:" << clientAddress;

        QJsonDocument doc = QJsonDocument::fromJson(message.toUtf8());
        if (doc.isObject()) {
            QJsonObject jsonObj = doc.object();
            QString clientName = jsonObj["clientName"].toString();

            // 存储客户端信息
            m_clientNames[socket] = clientName;
            m_clientIPs[clientAddress] = socket;

            qDebug()
                << "客户端信息已保存 - 名称:" << clientName
                << "IP:" << clientAddress;
        }

        // 断开lambda连接，改用常规消息处理
        socket->disconnect(socket, &QWebSocket::textMessageReceived, this, nullptr);
        connect(socket, &QWebSocket::textMessageReceived, this, &WebSocketServer::processTextMessage);
    });

    connect(socket, &QWebSocket::disconnected, this, &WebSocketServer::socketDisconnected);

    m_clients << socket;

    // 发送欢迎消息
    QJsonObject welcomeMessage;
    welcomeMessage["type"] = "system";
    welcomeMessage["content"] = "欢迎连接到Qt WebSocket服务器";
    QJsonDocument doc(welcomeMessage);
    socket->sendTextMessage(QString::fromUtf8(doc.toJson(QJsonDocument::Compact)));
}

void WebSocketServer::processTextMessage(const QString &message)
{
    QWebSocket *client = qobject_cast<QWebSocket *>(sender());
    if (!client)
        return;

    qDebug() << "收到消息:" << message;

    // 可以在这里处理消息或直接广播给所有客户端
    broadcastMessage(message);
}

void WebSocketServer::socketDisconnected()
{
    QWebSocket *client = qobject_cast<QWebSocket *>(sender());
    if (client) {
        QString clientAddress = client->peerAddress().toString();
        qDebug()
            << "客户端断开连接 - IP:" << clientAddress
            << "名称:" << m_clientNames.value(client);

        // 清理存储的信息
        m_clientNames.remove(client);
        m_clientIPs.remove(clientAddress);
        m_clients.removeAll(client);
        client->deleteLater();
    }
}

QWebSocket *WebSocketServer::findClientByName(const QString &name)
{
    for (auto it = m_clientNames.begin(); it != m_clientNames.end(); ++it)
    {
        if (it.value() == name)
        {
            return it.key();
        }
    }

    return nullptr;
}
